package ldh.im.client.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    private static HttpClient httpClient = HttpClients.custom().build();

    public HttpUtil() {
    }

    public static String post(String url, Map<String, Object> dataMap) throws Exception {
        if (httpClient == null) {
            httpClient = HttpClients.custom().build();
        }

        HttpPost httppost = new HttpPost(url);
        List<NameValuePair> params = new ArrayList();
        Iterator var4 = dataMap.entrySet().iterator();

        while(var4.hasNext()) {
            Map.Entry<String, Object> data = (Map.Entry)var4.next();
            params.add(new BasicNameValuePair((String)data.getKey(), data.getValue().toString()));
        }

        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        HttpResponse httpresponse = httpClient.execute(httppost);
        HttpEntity entity = httpresponse.getEntity();
        String body = EntityUtils.toString(entity);
        return body;
    }

    public static String body(String url, String json) throws IOException {
        if (httpClient == null) {
            httpClient = HttpClients.custom().build();
        }

        HttpPost httppost = new HttpPost(url);
        if (json != null) {
            httppost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
        }

        httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
        HttpResponse httpresponse = httpClient.execute(httppost);
        HttpEntity entity = httpresponse.getEntity();
        if (entity.getContentLength() == 0L) {
            return null;
        } else {
            String body = EntityUtils.toString(entity);
            return body;
        }
    }
}
